package com.qdlc.p2p.biz.processor.task.notices;

import java.text.MessageFormat;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.enums.ResponseOrderStatus;
import com.qd.p2p.adapter.response.QueryOrderStatusResponse;
import com.qd.p2p.baofoo.enums.P2pBizType;
import com.qdlc.p2p.biz.processor.event.BorrowRepayValueEvent;
import com.qdlc.p2p.biz.processor.event.RepayCollectNoticeEvent;
import com.qdlc.p2p.biz.processor.task.AbstractTaskProcessor;
import com.qdlc.p2p.biz.processor.task.pay.BorrowRepayPayTaskProcessor;
import com.qdlc.p2p.biz.service.CollectPayService;
import com.qdlc.p2p.common.constant.TradeStatus;
import com.qdlc.p2p.common.core.queue.QueueHandlers;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.core.queue.ValueEvent;
import com.qdlc.p2p.common.util.LogFactory;
import com.qdlc.p2p.common.util.MailUtil;
import com.qdlc.p2p.dal.dto.TppTradeLog;

/**
 * 还款
 *
 * @author wuaj
 */
@Service
public class RepayCollectNoticeProcessor extends AbstractTaskProcessor {
    protected static final Logger logger = LogFactory.TRADE_LOGGER;

    /**
     * 还款业务处理
     */
    @Resource
    @Qualifier("borrowRepayCollectService")
    private CollectPayService borrowRepayCollectService;

    @Resource
    @Qualifier("borrowRepayPayService")
    private CollectPayService borrowRepayPayService;

    @Resource
    private AdaptedRequestHandleService adaptedPayService;

    @Override
    public boolean supports(ValueEvent event) {
        return event instanceof RepayCollectNoticeEvent;
    }

    @Override
    public void process0(ValueEvent event) throws TaskProcessorException {
        RepayCollectNoticeEvent noticeEvent = (RepayCollectNoticeEvent) event;

        TradeStatus tradeStatus = noticeEvent.getTradeStatus(); // 交易状态
        double amount = noticeEvent.getDepositAmount(); // 投标金额
        TppTradeLog tppTradeLog = noticeEvent.getTppTradeLog(); // 交易log

        // 订单回查
        if (tradeStatus == TradeStatus.TRADE_STATUS_UN_KNOW) {
            QueryOrderStatusResponse response = adaptedPayService.queryOrderStatus(tppTradeLog.getOrderNo(), P2pBizType.REPAY.getType());
            ResponseOrderStatus orderStatus = response.getOrderStatus();
            if (orderStatus == ResponseOrderStatus.NO_ORDER || orderStatus == ResponseOrderStatus.FAILURE) {
                tradeStatus = TradeStatus.TRADE_STATUS_FAILED;
            } else if (orderStatus == ResponseOrderStatus.SUCCESS) {
                tradeStatus = TradeStatus.TRADE_STATUS_FINISHED;
            } else {
                // 状态还是未知 则抛出错误 重新调用
                throw new TaskProcessorException(event);
            }
        }

        String tradeStatusStr = tradeStatus.getStatus();
        logger.debug(MessageFormat.format("S 还款代收本息通知处理 -> 订单号:{0} 交易状态:{1} 交易金额:{2}", tppTradeLog.getOrderNo(), tradeStatusStr, amount));
        if (tradeStatus == TradeStatus.TRADE_STATUS_FINISHED) {
            borrowRepayCollectService.tradeFinish(tppTradeLog, tradeStatusStr, amount);
            try {
                // 多笔代付
                List<TppTradeLog> tppTradeLogs = borrowRepayPayService.createOrders(tppTradeLog);
                // 代付放入队列中
                BorrowRepayValueEvent borrowRepayValueEvent = new BorrowRepayValueEvent();
                borrowRepayValueEvent.setTppTradeLogs(tppTradeLogs);
                borrowRepayValueEvent.setTaskProcessorClass(BorrowRepayPayTaskProcessor.class);
                // 将事件放入到队列中
                QueueHandlers.put(borrowRepayValueEvent);
            } catch (Exception ex) {
                ex.printStackTrace();
                // 通知重新发起 代付还款金(本金+利息)
                MailUtil.sendMail("本息代付-订单生成失败", "本息代付订单生成失败", "");
            }
        } else if (tradeStatus == TradeStatus.TRADE_STATUS_FAILED) {
            borrowRepayCollectService.tradeFail(tppTradeLog, tradeStatusStr);
        }
        logger.debug(MessageFormat.format("E 还款代收本息通知处理 -> 订单号:{0} 交易状态:{1} 交易金额:{2}", tppTradeLog.getOrderNo(), tradeStatusStr, amount));
    }
}